from django.shortcuts import render, render_to_response, RequestContext, HttpResponse
from django.core.context_processors import csrf
from django.core.serializers.json import json
from django.utils import timezone
from contents.models import *
from utils import *

POINTS_NEEDED_TO_SHOW = 50

# Create your views here.
#def index(request):
	#context = {'contents': Content.objects.all()[:30] }

	#return render(request, 'contents/index.html', context)

def index(request, template='contents/index.html', page_template='contents/extra_contents.html'):
	contents = Content.objects.order_by('content_id').filter(points__gte=POINTS_NEEDED_TO_SHOW)

	if (request.user != 'AnonymousUser'):
		loadCalificationsForContents(contents, request.user.facebook_id)

	context = {
		'contents': contents,
		'page_template': page_template,
		'bests_contents': True,
		'all_contents': False,
	}
	if request.is_ajax():
		template = page_template
	return render(request, template, context)

def all_contents(request, template='contents/index.html', page_template='contents/extra_contents.html'):
	contents = Content.objects.order_by('content_id')

	if (request.user != 'AnonymousUser'):
		loadCalificationsForContents(contents, request.user.facebook_id)

	context = {
		'contents': contents,
		'page_template': page_template,
		'bests_contents': False,
		'all_contents': True,
	}
	if request.is_ajax():
		template = page_template
	return render(request, template, context)

def rate_content_ajax(request):
	if request.POST:
		requestValues = json.loads(request.body)
		response_data = {}

		calificationValue = requestValues['calification']

		#try:
		calificationDb = Calification.objects.filter(content_id=requestValues['content_id']).filter(user_id=requestValues['user_id'])


		if len(calificationDb) == 0:
			newCalification = Calification(content_id=requestValues['content_id'], user_id=requestValues['user_id'], calification=calificationValue, date=timezone.now())
			newCalification.save()
		else:
			calificationDb = calificationDb[0]
			calificationDb.date=timezone.now()

			if calificationDb.calification == '1' and calificationValue == '-1':
				content = Content.objects.get(content_id=requestValues['content_id'])
				content.likes -= 1
				content.dislikes += 1
				content.save()
			elif calificationDb.calification == '-1' and calificationValue == '1':
				content = Content.objects.get(content_id=requestValues['content_id'])
				content.likes += 1
				content.dislikes -= 1
				content.save()

		calificationDb.calification = calificationValue
		calificationDb.save()

		response_data['errno'] = 0
		#except Exception as err:
		#	response_data['errno'] = 1 if not hasattr(err, 'code') else err.code
		return HttpResponse(json.dumps(response_data), content_type="application/json")

def login_modal(request):
	return render(request, 'contents/loginModal.html', {})

def foo(request):
	return render(request, 'contents/foo.html', {})